package com.wjk.cms.util.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class WxApiUtil {

    public static JSONObject get(String url) throws Exception {
        log.info("WxApiUtil.get - " + url);
        URL urlObj = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
        httpConn.setRequestMethod("GET");
        httpConn.setDoOutput(true);
        httpConn.setConnectTimeout(10000);
        httpConn.setReadTimeout(10000);
        int code = httpConn.getResponseCode();
        if (code != 200) return null;
        BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        StringBuffer infoSB = new StringBuffer();
        String resp = null;
        while ((resp = br.readLine()) != null) {
            infoSB.append(resp);
        }
        String responseText = infoSB.toString();
        log.info("Response of GET " + url + "\n" + responseText);
        return JSON.parseObject(infoSB.toString());
    }

    public static JSONObject post(String url, String data) throws Exception {
        log.info("WxApiUtil.post - " + url + "\n" + data);
        URL urlObj = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
        httpConn.setRequestMethod("POST");
        httpConn.setConnectTimeout(10000);
        httpConn.setReadTimeout(10000);
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);

        httpConn.connect();
        OutputStream os = httpConn.getOutputStream();
        os.write(data.getBytes("UTF-8"));
        os.flush();

        int code = httpConn.getResponseCode();
        if (code != 200) return null;
        BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        StringBuffer infoSB = new StringBuffer();
        String resp = null;
        while ((resp = br.readLine()) != null) {
            infoSB.append(resp);
        }
        String responseText = infoSB.toString();
        log.info("Response of POST " + url + "\n" + responseText);
        return JSON.parseObject(infoSB.toString());
    }

    public static BufferedImage getForImage(String url) throws Exception {
        log.info("WxApiUtil.postForImage - " + url);
        URL urlObj = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
        httpConn.setRequestMethod("GET");
        httpConn.setDoOutput(true);
        httpConn.setConnectTimeout(10000);
        httpConn.setReadTimeout(10000);
        int code = httpConn.getResponseCode();
        if (code != 200) return null;
        try {
            return ImageIO.read(httpConn.getInputStream());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static BufferedImage postForImage(String url, String data) throws Exception {
        log.info("WxApiUtil.postForImage - " + url + "\n" + data);
        URL urlObj = new URL(url);
        HttpURLConnection httpConn = (HttpURLConnection) urlObj.openConnection();
        httpConn.setRequestMethod("POST");
        httpConn.setConnectTimeout(10000);
        httpConn.setReadTimeout(10000);
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);

        httpConn.connect();
        OutputStream os = httpConn.getOutputStream();
        os.write(data.getBytes("UTF-8"));
        os.flush();


        int code = httpConn.getResponseCode();
        log.info("content:"+httpConn.getContent());

        log.info("postForImage 返回code:"+code);
        if (code != 200) return null;
        try {
            BufferedImage bim =ImageIO.read(httpConn.getInputStream());
            if(bim==null){
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                StringBuffer infoSB = new StringBuffer();
                String resp = null;
                while ((resp = br.readLine()) != null) {
                    infoSB.append(resp);
                }
                log.info("postForImage 错误:"+infoSB.toString());
            }
            return bim;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static JSONObject uploadMedia(String accessToken, String fileType, String filePath) throws Exception {
        //返回结果
        String result = null;
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IOException("文件不存在");
        }
        String urlString = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=" + fileType;
        log.info("WxApiUtil.uploadMedia - " + urlString);
        URL url = new URL(urlString);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");//以POST方式提交表单
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);//POST方式不能使用缓存
        //设置请求头信息
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        //设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        //请求正文信息
        //第一部分
        StringBuilder sb = new StringBuilder();
        sb.append("--");//必须多两条道
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        System.out.println("sb:" + sb);

        //获得输出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        //输出表头
        out.write(sb.toString().getBytes("UTF-8"));
        //文件正文部分
        //把文件以流的方式 推送道URL中
        DataInputStream din = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] buffer = new byte[1024];
        while ((bytes = din.read(buffer)) != -1) {
            out.write(buffer, 0, bytes);
        }
        din.close();
        //结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");//定义数据最后分割线
        out.write(foot);
        out.flush();
        out.close();
        if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {
            StringBuffer strbuffer = null;
            BufferedReader reader = null;
            try {
                strbuffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String lineString = null;
                while ((lineString = reader.readLine()) != null) {
                    strbuffer.append(lineString);

                }
                if (result == null) {
                    result = strbuffer.toString();
                    System.out.println("result:" + result);
                }
            } catch (IOException e) {
                System.out.println("发送POST请求出现异常！" + e);
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

    public static JSONObject uploadMedia(String accessToken, String fileName, String formatName, BufferedImage image) throws Exception {
        String fileType = "image";
        //返回结果
        String result = null;
        if (image == null) {
            throw new IOException("文件不存在");
        }
        String urlString = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=" + fileType;
        log.info("WxApiUtil.uploadMedia - " + urlString);
        URL url = new URL(urlString);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");//以POST方式提交表单
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);//POST方式不能使用缓存
        //设置请求头信息
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        //设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        //请求正文信息
        //第一部分
        StringBuilder sb = new StringBuilder();
        sb.append("--");//必须多两条道
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\"; filename=\"" + fileName + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        System.out.println("sb:" + sb);

        //获得输出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        //输出表头
        out.write(sb.toString().getBytes("UTF-8"));
        //文件正文部分
        //把文件以流的方式 推送道URL中
        ImageIO.write(image, formatName, out);
        //结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");//定义数据最后分割线
        out.write(foot);
        out.flush();
        out.close();
        if (HttpsURLConnection.HTTP_OK == conn.getResponseCode()) {
            StringBuffer strbuffer = null;
            BufferedReader reader = null;
            try {
                strbuffer = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String lineString = null;
                while ((lineString = reader.readLine()) != null) {
                    strbuffer.append(lineString);

                }
                if (result == null) {
                    result = strbuffer.toString();
                    System.out.println("result:" + result);
                }
            } catch (IOException e) {
                System.out.println("发送POST请求出现异常！" + e);
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

}
